<template>
  <div v-loading="loading" class="big-upload">
    <el-upload
      ref='upload'
      :class="{ hide: hideUpload }"
      action=""
      :limit='1'
      list-type="text"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :http-request='uploadFile'
      :on-exceed='handleExceed'
      :disabled="disabled"
    >
      <el-button type="primary">点击上传</el-button>
      <template #file='{file}'>
        <el-progress  type="line" :percentage="state.percent"
        ></el-progress>
      </template>
    </el-upload>
    <span v-if="empty && disabled" class="empty-content">{{ emptyText }}</span>
  </div>
</template>

<script setup>
// import { getSysparamFileServer } from '@/api/system'
import {
  Delete,
  ZoomIn,
  Bottom,
  Edit,
  Search,
  Share,
  Upload,
  Plus,
  VideoPlay
} from '@element-plus/icons-vue'
// import { mapGetters } from 'vuex'
import { changeSize } from '@/utils'
// import API from '@/api/common'
import { useUserStore } from '@/pinia/modules/user'
import { ElMessage } from 'element-plus'
// import {uploadBigFile} from '@/api/api.js'
const emit = defineEmits(['update:bizId', 'success','videoInfos'])
const ALL_TYPE = [
  'png',
  'jpg',
  'jpeg',
  'bmp',
  'gif',
  'jfif',
  'txt',
  'xlsx',
  'xls',
  'doc',
  'docx',
  'pdf',
  'ppt',
  'pptx',
  'zip',
  'mp4',
  'webp',
  'pdf',
  'pdfx'
]
const IMG = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'jfif', 'webp']
const EXCEL = ['xlsx', 'xls']
const WORD = ['doc', 'docx']
const PPT = ['ppt', 'pptx']
const VIDEO = ['mp4']
const PDF = ['pdf', 'pdfx']
const userStore = useUserStore()
const props = defineProps({
  validateField: {
    type: Function,
    default: null
  },
  disabled: {
    type: Boolean,
    default() {
      return false
    }
  },
  emptyText: {
    type: String,
    default: '暂无附件'
  },
  limit: {
    type: String,
    default: '10'
  },
  bizId: {
    type: String,
    default: ''
  },
  bizType: {
    type: String,
    default: ''
  },
  fileSize: {
    type: Number,
    default: 8
  },
  allowUploadTypes: {
    type: Array,
    default: () => ['jpg', 'jpeg', 'png', 'doc', 'docx', 'pdf']
  }
})

const fileUrl = ref('')
const videoDialog = ref(false)
const fileList = ref([])
const tempFiles = ref([])
const loading = ref(false)
const headers = ref({
  Authorization: userStore.token
})
const selectImg = ref([])
const showViewer = ref(false)
const hideUpload = ref(false)
const empty = ref(false)
const baseUrl = ref('/api/service/oss/aliyun/upload') // 上传的路径
const state = reactive({
  percent: 100
})
const upload = ref(null)

const getImageUrl = name => {
  return new URL(`../../assets/img/file-icon/${name}.png`, import.meta.url).href
}

const init = async fileUrl => {
  // 获取已有图片或文件并处理
  loading.value = true
  const res = await getAllFiles(`${fileUrl}/metadatas/by_ids/${props.bizId}`)
  if (!res.data || res.data.length === 0) {
    empty.value = true
    loading.value = false
    if (props.disabled) {
      hideUpload.value = true
    }
    return
  }
  let notImgFiles = []
  let imgFilesInfo = []
  let imgFiles = res.data.filter(item => {
    if (calFileType(item.name) !== 'img') {
      notImgFiles.push(item)
    }
    return calFileType(item.name) === 'img'
  })

  if (notImgFiles && notImgFiles.length > 0) {
    notImgFiles = notImgFiles.map(item => {
      return {
        imgId: item.id,
        fullUrl: fileUrl + '/download/' + item.id,
        bigUrl: fileUrl + '/download/' + item.id,
        url: fileUrl + '/download/' + item.id,
        fileType: calFileType(item.name),
        fileName: item.name
      }
    })
  }

  if (imgFiles && imgFiles.length > 0) {
    let tempFilesArr = imgFiles.map(async (element, index) => {
      const res = await timedGetText(fileUrl + '/download_base64/' + element.id)
      return {
        imgId: res.data.id,
        fullUrl: 'data:image/jpg;base64,' + res.data.dataBase64,
        bigUrl: 'data:image/jpg;base64,' + res.data.dataBase64,
        url: 'data:image/jpg;base64,' + res.data.dataBase64,
        fileType: calFileType(res.data.name),
        fileName: res.data.name
      }
    })
    Promise.all(tempFilesArr).then(res => {
      imgFilesInfo = res
      fileList.value = [...res, ...notImgFiles]
      loading.value = false
      empty.value = false
    })
  } else {
    if (!res.data || res.data.length === 0) {
      empty.value = true
    }
    fileList.value = [...imgFilesInfo, ...notImgFiles]
    loading.value = false
  }
  /*   console.log('imgFilesInfo', imgFilesInfo)
  fileList.value = [...imgFilesInfo, ...notImgFiles]
  loading.value = false
  empty.value = false */

  /*   const idsArray = props.bizId.split(',')
  idsArray.splice(idsArray.length - 1, 1)
  // console.log('idsArray.length', idsArray.length)
  if (idsArray.length === 0) {
    empty.value = true
    loading.value = false
    return
  }

  let tempFilesArr = idsArray.map(async (element, index) => {
    const res = await timedGetText(fileUrl + '/download_base64/' + element)
    // const res = await timedGetText(fileUrl + '/download/' + element)
    return {
      imgId: res.data.id,
      fullUrl: 'data:image/jpg;base64,' + res.data.dataBase64,
      bigUrl: 'data:image/jpg;base64,' + res.data.dataBase64,
      url: 'data:image/jpg;base64,' + res.data.dataBase64,
      fileType: calFileType(res.data.name),
      fileName: res.data.name
    }
  })
  Promise.all(tempFilesArr).then(res => {
    fileList.value = res
    loading.value = false
    empty.value = false
  }) */
}

const getAllFiles = url => {
  return new Promise((resolve, reject) => {
    var request = new XMLHttpRequest()
    request.open('GET', url)
    request.setRequestHeader('Authorization', userStore.token)
    request.onreadystatechange = function () {
      if (request.readyState !== 4) return
      if (request.status === 200) {
        resolve(JSON.parse(request.responseText))
      }
    }
    request.send()
  })
}

const timedGetText = url => {
  return new Promise((resolve, reject) => {
    var request = new XMLHttpRequest()
    request.open('GET', url)
    request.setRequestHeader('Authorization', userStore.token)
    request.onreadystatechange = function () {
      if (request.readyState !== 4) return
      if (request.status === 200) {
        resolve(JSON.parse(request.responseText))
      }
    }
    request.send()
  })
}

watch(
  () => fileList.value,
  val => {
    if (props.disabled) {
      hideUpload.value = true
      return
    }
    if (val.length > 0) {
      let ids = ''
      val.forEach(item => {
        if (item.imgId) {
          ids = ids + item.imgId + ','
        }
      })

      emit('update:bizId', ids)
      emit('success')
      if (props.validateField) {
        props.validateField()
      }
    } else {
      emit('update:bizId', '')
      if (props.validateField) {
        props.validateField()
      }
    }

    if (val.length >= props.limit) {
      hideUpload.value = true
    } else {
      hideUpload.value = false
    }
  },
  { deep: true }
)

/* watch(
  () => props.bizId,
  async val => {
    if (val) {
      try {
        if (val) {
          console.log('init(userStore.fileUrl)', val)
          // init(userStore.fileUrl)
        }
      } catch (error) {
        // console.log('error', error)
      }
    } else {
      console.log('init(userStore.fileUrl)22', val)
      // empty.value = true
      // loading.value = false
    }
  },
  { immediate: true }
) */

const videoPlay = file => {
  videoDialog.value = true
}

const beforeUpload = file => {
  hideUpload.value = true

  if (props.allowUploadTypes.indexOf('mp4') != -1) {
    let url = URL.createObjectURL(file)
    var audioElement = new Audio(url)
    audioElement.addEventListener('loadedmetadata', function () {
      let playTime = audioElement.duration //playTime就是当前视频长度
      emit('videoInfos',{duration:Math.floor(playTime),type:file.type,size: changeSize(file.size)})
    })
  }

  if (props.allowUploadTypes.length > 0) {
    const fileType = file.name.replace(/.+\./, '')
    const result = ALL_TYPE.find(item => item == fileType)
    const isConformType = props.allowUploadTypes.indexOf(result) === -1
    if (isConformType) {
      ElMessage.error(`请上传${props.allowUploadTypes.join('，')}格式文件!`)
      hideUpload.value = false
      return !isConformType
    }
  }

  // const isConform = file.size / 1024 / 1024 > props.fileSize
  //
  // if (isConform) {
  //   ElMessage.error(`上传文件大小不能超过${props.fileSize}MB!`)
  //   hideUpload.value = false
  //   loading.value = false
  // }
  // return !isConform
  return true;
}

const calFileType = url => {
  const fileType = url.replace(/.+\./, '')
  const result = ALL_TYPE.find(item => item == fileType)
  if (IMG.indexOf(result) > -1) return 'img'
  if (EXCEL.indexOf(result) > -1) return 'excel'
  if (WORD.indexOf(result) > -1) return 'word'
  if (PPT.indexOf(result) > -1) return 'ppt'
  if (VIDEO.indexOf(result) > -1) return 'video'
  if (PDF.indexOf(result) > -1) return 'pdf'
  return result ? fileType : 'unknown'
}


const delFile = file => {
  fileList.value = fileList.value.filter(item => item.imgId != file.imgId)
}

const download = file => {
  window.open(file.fullUrl)
}

const viewImg = file => {
  showViewer.value = true
  selectImg.value = [file.bigUrl]
}

const closeViewer = () => {
  showViewer.value = false
}

const uploadFile = async ({data, file})=>{
  state.percent = 0;
  const res = await uploadBigFile(file, (percent)=>{
    state.percent = percent;
  })
  if (res.succeed) {
    emit('update:bizId', res.data.id)
  } else {
    ElMessage.error(res.msg) // 后加的 因request.js未生效
  }
}

const handleExceed =  (files) => {
  upload.value.clearFiles()
  const file = files[0]
  upload.value.handleStart(file)
  upload.value.submit()
}

onBeforeMount(() => {
  if (props.bizId && props.bizId !== '--') {
    init(userStore.fileUrl)
  } else {
    empty.value = true
    if (props.disabled) {
      hideUpload.value = true
    }
    loading.value = false
  }
})
</script>

<style lang="scss" scoped>
.file-type-icon {
  width: 48px;
  margin-left: 49px;
  margin-top: 40px;
  height: 50px;
}

.big-upload {
  width: 100%;
  min-height: 100px;
  .el-progress--line{
    width: 100%;
  }
  .hide {
    :deep(.el-upload--picture-card) {
      display: none;
    }
  }

  :deep(.el-upload-list__item:first-child) {
    margin-top: 0;
  }

  :deep(.el-upload-list--picture-card) {
    line-height: 0;

    .el-upload-list__item {
      margin: 8px;
    }
  }

  :deep(.el-upload--picture-card) {
    margin: 8px;
  }

  .empty-content {
    height: 164px;
    line-height: 164px;
    font-size: 13px;
    padding-left: 50%;
    position: relative;
    left: -27px;
    color: #333;
  }

  .file-name {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: middle;
    color: #999;
    padding: 0 10px;
    text-align: center;
  }
}
</style>
